﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
//using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;
using MvCamCtrl.NET;
using MvCamCtrl.NET.CameraParams;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace test
{
    public partial class Form1 : Form
    {



        private HWindow hwindow;
        public double x, y, angle;
        int w_width;
        int w_height;
        // private CCamera m_MyCamera = new CCamera();
        MyCamera.MV_CC_DEVICE_INFO_LIST m_pDeviceList;
        private MyCamera m_pMyCamera;
        bool m_bGrabbing=true ;
        HDrawingObject doRoi = null;

        //MyCamera.MV_CC_DEVICE_INFO_LIST m_pDeviceList;//设备列表
        private MyCamera.MVCC_INTVALUE stParam;//用于接收特定的参数
                                               //为读取、保存图像创建的数组
        UInt32 m_nBufSizeForDriver = 3072 * 2048 * 3;
        byte[] m_pBufForDriver = new byte[3072 * 2048 * 3];
        UInt32 m_nBufSizeForSaveImage = 3072 * 2048 * 3 * 3 + 2048;
        byte[] m_pBufForSaveImage = new byte[3072 * 2048 * 3 * 3 + 2048];
        //要转成的Halcon图像
        HImage image = new HImage();

        //绘画对象
        //绘图对象
       // private HDrawingObject drawingObject = new HDrawingObject();
        //线ROI
       // private Line line = new Line();
        //框ROI
      //  private Rectangle2 rectangle2 = new Rectangle2();



        public Form1()
        {
            InitializeComponent();
            hwindow = hSmartWindowControl1.HalconWindow;//初始化窗口变量s
            w_width = hSmartWindowControl1.Size.Width;
            w_height = hSmartWindowControl1.Size.Height;
            //this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.my_MouseWheel);

            m_pDeviceList = new MyCamera.MV_CC_DEVICE_INFO_LIST();
            m_pMyCamera = new MyCamera();

            DeviceListAcq();
        }
        private void DeviceListAcq()
        {
            int nRet;
            // ch:创建设备列表 || en: Create device list
            System.GC.Collect();
            cbDeviceList.Items.Clear();
            nRet = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref m_pDeviceList);
            if (MyCamera.MV_OK != nRet)
            {
                MessageBox.Show("Enum Devices Fail");
                return;
            }

            // ch:在窗体列表中显示设备名 || Display the device'name on window's list
            for (int i = 0; i < m_pDeviceList.nDeviceNum; i++)
            {
                MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
                if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
                    MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));
                    if (gigeInfo.chUserDefinedName != "")
                    {
                        cbDeviceList.Items.Add("GigE: " + gigeInfo.chUserDefinedName + " (" + gigeInfo.chSerialNumber + ")");
                    }
                    else
                    {
                        cbDeviceList.Items.Add("GigE: " + gigeInfo.chManufacturerName + " " + gigeInfo.chModelName + " (" + gigeInfo.chSerialNumber + ")");
                    }
                }
                else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
                    MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_USB3_DEVICE_INFO));
                    if (usbInfo.chUserDefinedName != "")
                    {
                        cbDeviceList.Items.Add("USB: " + usbInfo.chUserDefinedName + " (" + usbInfo.chSerialNumber + ")");
                    }
                    else
                    {
                        cbDeviceList.Items.Add("USB: " + usbInfo.chManufacturerName + " " + usbInfo.chModelName + " (" + usbInfo.chSerialNumber + ")");
                    }
                }
            }

            //.ch: 选择第一项 || en: Select the first item
            if (m_pDeviceList.nDeviceNum != 0)
            {
                cbDeviceList.SelectedIndex = 0;
            }
        }
        /*private void my_MouseWheel(object sender, MouseEventArgs e)
        {
            System.Drawing.Point pt = this.Location;
            int leftBorder = hSmartWindowControl1.Location.X;
            int rightBorder = hSmartWindowControl1.Location.X + hSmartWindowControl1.Size.Width;
            int topBorder = hSmartWindowControl1.Location.Y;
            int bottomBorder = hSmartWindowControl1.Location.Y + hSmartWindowControl1.Size.Height;
            if (e.X > leftBorder && e.X < rightBorder && e.Y > topBorder && e.Y < bottomBorder)
            {
                MouseEventArgs newe = new MouseEventArgs(e.Button, e.Clicks, e.X - pt.X, e.Y - pt.Y, e.Delta);
                hSmartWindowControl1.HSmartWindowControl_MouseWheel(sender, newe);
            }
        }*/
        private void my_MouseWheel(object sender, HMouseEventArgs e)
        {
            HTuple Zoom, Row, Col, Button;
            HTuple Row0, Column0, Row00, Column00, Ht, Wt, r1, c1, r2, c2;
            if (e.Delta > 0)
            {
                Zoom = 1.5;
            }
            else
            {
                Zoom = 0.5;
            }
            HOperatorSet.GetMposition(hSmartWindowControl1.HalconWindow, out Row, out Col, out Button);
            HOperatorSet.GetPart(hSmartWindowControl1.HalconWindow, out Row0, out Column0, out Row00, out Column00);
            Ht = Row00 - Row0;
            Wt = Column00 - Column0;
            if (Ht * Wt < 32000 * 32000 || Zoom == 1.5)//普通版halcon能处理的图像最大尺寸是32K*32K。如果无限缩小原图像，导致显示的图像超出限制，则会造成程序崩溃
            {
                r1 = (Row0 + ((1 - (1.0 / Zoom)) * (Row - Row0)));
                c1 = (Column0 + ((1 - (1.0 / Zoom)) * (Col - Column0)));
                r2 = r1 + (Ht / Zoom);
                c2 = c1 + (Wt / Zoom);
                HOperatorSet.SetPart(hSmartWindowControl1.HalconWindow, r1, c1, r2, c2);
                HOperatorSet.ClearWindow(hSmartWindowControl1.HalconWindow);
                //HOperatorSet.DispObj(ho_Image, hSmartWindowControl1.HalconWindow);
            }
        }
        private void ImageZoomShow(HObject HoIage, HWindow hW,int i_width,int i_height)
        {
            HTuple hv_Width = new HTuple();
            HTuple hv_Height = new HTuple();
            bool needResizeImage = true;
            HOperatorSet.GetImageSize(HoIage, out hv_Width, out hv_Height);
            int im_width = int.Parse(hv_Width.ToString());
            int im_height = int.Parse(hv_Height.ToString());
            double im_AspectRatio = (double)(im_width) / (double)(im_height);
            //int im_width=hW.GetLineWidth
            double w_AspectRatio = (double)(i_width) / (double)(i_height);

            HOperatorSet.SetSystem("int_zooming", "false");//图像缩放之前最好将此参数设置为false.
            HTuple para = new HTuple("constant");
            HObject ho_zoomImage;
            HOperatorSet.GenEmptyObj(out ho_zoomImage);

            ho_zoomImage.Dispose();
            if (i_width < im_width && im_AspectRatio > w_AspectRatio)
            {
                //超宽图像               
                HOperatorSet.ZoomImageSize(HoIage, out ho_zoomImage, w_width, w_width / im_AspectRatio, para);
            }
            else if(i_height < im_height && im_AspectRatio < w_AspectRatio)
            {
                //超高图像                
                HOperatorSet.ZoomImageSize(HoIage, out ho_zoomImage, w_height * im_AspectRatio, w_height, para);
            }
            else
            {
                needResizeImage = false;
            }

            hW.SetPart(0, 0, -2, -2);
            if (needResizeImage)
            {
                hwindow.DispObj(ho_zoomImage);
            }
            else
            {
                hwindow.DispObj(HoIage);
            }

            ho_zoomImage.Dispose();
            hv_Width.Dispose();
            hv_Height.Dispose();
        }
        HTuple hv_AcqHandle = new HTuple();
      
        private void Form1_Load(object sender, EventArgs e)
        {
            //建立相机连接
           // if (!InitialVision1("44a6421b59f9_Hikrobot_MVCA05012GC"))
            //{
            //    // CAutoGL.ShowMessage("婴童项目", "照相机通讯连接失败，请先退出，确认相机电源通讯是否正常!", "Please choose one TMR tester at least!", (int)CAutoGL.MSG.ERROR, 1);
            //    return;
                //goto ExitStart;
           // }
        }
        public bool InitialVision1(string stn)
        {

            int k = 0;
        tryAgain:
            try
            {
                HTuple hv_AcqHandle = new HTuple();
                HObject ho_Image = null;
                HOperatorSet.GenEmptyObj(out ho_Image);
                hv_AcqHandle.Dispose();
                //        HOperatorSet.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "progressive",
                //-1, "gray", -1, "false", "default", "camera1", 0,
                //-1, out cAutoGL.hv_AcqHandle);
                //          HOperatorSet.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "progressive",
                //-1, "default", -1, "false", "default", "'c42f90ff24ec_GEV_PMS0130B24BDC'",
                //0, -1, out  CAutoGL.hv_AcqHandle);
                 HOperatorSet.OpenFramegrabber("GigEVision2", 0, 0, 0, 0, 0, 0, "progressive",
                  -1, "gray", -1, "false", "default", stn,
                  0, -1, out hv_AcqHandle);
               
              //  HOperatorSet.OpenFramegrabber("MediaFoundation", 0, 0, 0, 0, 0, 0, "progressive",
        //-1, "default", -1, "false", "default", "Integrated_Webcam_vid_0c45 & pid_6730 & mi_00#6&30b7ece1&0&0000",
        //0, -1, out hv_AcqHandle);



                //            HOperatorSet.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "progressive",
                //-1, "default", -1, "false", "default", "c42f90ff395f_GEV_MVCE10030GM",
                //0, -1, out  CAutoGL.hv_AcqHandle);
                //HOperatorSet.SetFramegrabberParam(cAutoGL.hv_AcqHandle, "contrast", 132);

                HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                //  HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                //HOperatorSet .cameragetim
                //HOperatorSet.SetFramegrabberParam(cAutoGL.hv_AcqHandle, "exposure_mode", 0);
                //CAutoGL.UpdateGUI((int)CAutoGL.UpdateItem.RcvListBox, "连接照相机1成功--------%2");

                HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
                //HOperatorSet.SetFramegrabberParam(CAutoGL.hv_AcqHandle, "ExposureTime", CAutoGL.selExposure);
               // Thread.Sleep(100);
                // hwindow.SetPart(0, 0, -2, -2);
               // HImage img = new HImage(ho_Image);
                //HImage ho_zoomImage = img.ZoomImageSize(w_width, w_width, "constant");
               // hwindow.DispObj(ho_Image);
                ImageZoomShow(ho_Image, hwindow, w_width, w_height);


                return true;
            }
            catch (Exception Ex)
            {
                k++;
                if (k < 4)
                {
                    //Thread.Sleep(50);
                    goto tryAgain;
                }
                else
                {

                    // CAutoGL.UpdateGUI((int)CAutoGL.UpdateItem.RcvListBox, "连接照相机1失败--------%2");
                    return false;
                }

            }


        }

      

        public bool ActionK(HWindow ho_WHD)
        {

            // IntPtr m_ImageBuffer;
            HObject ho_Image;

        

          


            HTuple hv_I = null, hv_HomMat2DRotate = new HTuple(), hv_HomMat2DScale = new HTuple();
            HTuple hv_HomMat2DRotate1 = new HTuple(), hv_HomMat2DScale1 = new HTuple();
         
          
      
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_Image);
            //HOperatorSet.GenEmptyObj(out ho_Edges);

            //HOperatorSet.GenEmptyObj(out ho_Circle);



            //Thread.Sleep(100);
            try
            {

                // if (m_ImageBuffer != null)
                //{
                //  if (m_ImageBuffer != null)
                // {
                //HOperatorSet.GenImageInterleaved(out FileImage1, cAutoGL.m_ImageBuffer, "rgb", cAutoGL.w, cAutoGL.h, -1, "byte", cAutoGL.w, cAutoGL.h, 0, 0, -1, 0);
                //cAutoGL.hVision.GrabAsync(ho_WHD);
                //HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
                //HOperatorSet.SetFramegrabberParam(CAutoGL.hv_AcqHandle, "ExposureTime", CAutoGL.selExposure);
                //Thread.Sleep(100);

                ho_WHD.DispObj(ho_Image);

                ho_Image.Dispose();
                return true;

            }
            catch (Exception ex)
            {
                // ho_WHD.DispObj(ho_Image);
            

                //ho_Edges.Dispose();
              
                return false;
            }
            }

        private void BtnTe_Click(object sender, EventArgs e)
        {
            DeviceListAcq();
        }

        private void 相机打开_Click(object sender, EventArgs e)
        {
            if (m_pDeviceList.nDeviceNum == 0 || cbDeviceList.SelectedIndex == -1)
            {
                MessageBox.Show("No device,please select");
                return;
            }
            int nRet = -1;

            //ch:获取选择的设备信息 | en:Get selected device information
            MyCamera.MV_CC_DEVICE_INFO device =
                (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[cbDeviceList.SelectedIndex],
                                                              typeof(MyCamera.MV_CC_DEVICE_INFO));

            nRet = m_pMyCamera.MV_CC_CreateDevice_NET(ref device);
            if (MyCamera.MV_OK != nRet)
            {
                return;
            }

            // ch:打开设备 | en:Open device
            nRet = m_pMyCamera.MV_CC_OpenDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                MessageBox.Show("Open Device Fail");
                return;
            }

            // ch:设置触发模式为off || en:set trigger mode as off
            m_pMyCamera.MV_CC_SetEnumValue_NET("AcquisitionMode", 2);
            m_pMyCamera.MV_CC_SetEnumValue_NET("TriggerMode", 0);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (m_bGrabbing)
            {
                m_bGrabbing = false;
                // ch:停止抓图 || en:Stop grab image
                m_pMyCamera.MV_CC_StopGrabbing_NET();

                // ch: 控件操作 || en: Control operation
              //  SetCtrlWhenStopGrab();
            }

            // ch:关闭设备 || en: Close device
            m_pMyCamera.MV_CC_CloseDevice_NET();

            // ch: 控件操作 || en: Control operation
            //SetCtrlWhenClose();

            m_bGrabbing = false;
        }
        public HImage ReadImage()
        {
            int nRet;
            //MyCamera.MVCC_INTVALUE stParam = new MyCamera.MVCC_INTVALUE();
            UInt32 nPayloadSize = 0;
            nRet = m_pMyCamera.MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
            if (MyCamera.MV_OK != nRet)
            {
                return null;
            }
            nPayloadSize = stParam.nCurValue;
            if (nPayloadSize > m_nBufSizeForDriver)
            {
                m_nBufSizeForDriver = nPayloadSize;
                m_pBufForDriver = new byte[m_nBufSizeForDriver];
                m_nBufSizeForSaveImage = m_nBufSizeForDriver * 3 + 2048;
                m_pBufForSaveImage = new byte[m_nBufSizeForSaveImage];
            }

            IntPtr pData = Marshal.UnsafeAddrOfPinnedArrayElement(m_pBufForDriver, 0);
            MyCamera.MV_FRAME_OUT_INFO_EX stFrameInfo = new MyCamera.MV_FRAME_OUT_INFO_EX();
            nRet = m_pMyCamera.MV_CC_GetOneFrameTimeout_NET(pData, m_nBufSizeForDriver, ref stFrameInfo, 1000);//获取一帧图像，超时时间设置为1000
            if (MyCamera.MV_OK != nRet)
            {
                return null;
            }

            HImage image = new HImage();

            //采集的是黑白图像，利用Halcon图像库中的GenImage1算子来构建图像
            image.GenImage1("byte", (int)stFrameInfo.nWidth, (int)stFrameInfo.nHeight, pData);
            return image;
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
           // HTuple hWind = hWindowControl1.HalconWindow;

            HTuple width, height;

            HObject hv_image;
            HOperatorSet.GenEmptyObj(out hv_image);
            hv_image.Dispose();


            int nRet = MyCamera.MV_OK;
            //选择触发模式
            nRet = m_pMyCamera.MV_CC_SetEnumValue_NET("TriggerMode", 1);
            if (nRet != MyCamera.MV_OK)
            {
                MessageBox.Show("Set TriggerMode Fail");
                return;
            }
            //选择软触发模式
            nRet = m_pMyCamera.MV_CC_SetEnumValue_NET("TriggerSource", 7);
            if (nRet != MyCamera.MV_OK)
            {
                MessageBox.Show("Set TriggerSource Fail");
                return;
            }

            //曝光时间
            nRet= m_pMyCamera.MV_CC_SetEnumValue_NET("ExposureAuto", 0);
            // nRet = m_pMyCamera.MV_CC_SetEnumValue_NET("ExposureTime", 30000);
            nRet = m_pMyCamera.MV_CC_SetExposureTime_NET(float.Parse(tbExposure.Text));


           /// m_pMyCamera.SetEnumValue("ExposureAuto", 0);

          //  nRet = m_pMyCamera.MV_CC_SetEnumValue_NET("ExposureTime", flaot.Parse(tbExposure.Text));
            if (nRet != MyCamera.MV_OK)
            {
                MessageBox.Show("设置曝光时间失败！");
            }


            //触发一次
            // nRet = m_pMyCamera.MV_CC_SetCommandValue_NET("TriggerSoftware");
            // if (MyCamera.MV_OK != nRet)
            // {
            //     MessageBox.Show("Trigger Fail");
            // }
            // ch:开启抓图 | en:start grab  开始采集图像
            nRet = m_pMyCamera.MV_CC_StartGrabbing_NET();
            if (MyCamera.MV_OK != nRet)
            {
                MessageBox.Show("Start Grabbing Fail");
                return;
            }
            m_bGrabbing = true;




            Thread hReceiveImageThreadHandle = new Thread(ReceiveImageWorkThread);
            hReceiveImageThreadHandle.Start(m_pMyCamera);



           // hv_image = this.ReadImage();
           // hwindow.DispObj(hv_image);
           // ImageZoomShow(hv_image, hwindow, w_width, w_height);
            
            // HOperatorSet.GetImageSize(hv_image, out width, out height);
            // HOperatorSet.SetPart(hwindow, 0, 0, height - 1, width - 1);
            //HOperatorSet.DispObj(hv_image, hwindow);
        }
        private bool IsColorPixelFormat(MyCamera.MvGvspPixelType enType)
        {
            switch (enType)
            {
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BGR8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGBA8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BGRA8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_YUYV_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12_Packed:
                    return true;
                default:
                    return false;
            }
        }
        private bool IsMonoPixelFormat(MyCamera.MvGvspPixelType enType)
        {
            switch (enType)
            {
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
                    return true;
                default:
                    return false;
            }
        }


        public void HalconDisplay(HTuple hWindow, HObject Hobj)
        {
            try
            {
                HOperatorSet.DispObj(Hobj, hWindow); // Display the image
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
        public void ReceiveImageWorkThread(object obj)
        {
            int nRet = MyCamera.MV_OK;
            MyCamera device = obj as MyCamera;
            MyCamera.MV_FRAME_OUT stFrameOut = new MyCamera.MV_FRAME_OUT();

            IntPtr pImageBuf = IntPtr.Zero;
            int nImageBufSize = 0;

            HObject Hobj = new HObject();
            IntPtr pTemp = IntPtr.Zero;

            while (m_bGrabbing)
            {
                nRet = device.MV_CC_GetImageBuffer_NET(ref stFrameOut, 1000);
                if (MyCamera.MV_OK == nRet)
                {
                    if (IsColorPixelFormat(stFrameOut.stFrameInfo.enPixelType))
                    {
                        if (stFrameOut.stFrameInfo.enPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed)
                        {
                            pTemp = stFrameOut.pBufAddr;
                        }
                        else
                        {
                            if (IntPtr.Zero == pImageBuf || nImageBufSize < (stFrameOut.stFrameInfo.nWidth * stFrameOut.stFrameInfo.nHeight * 3))
                            {
                                if (pImageBuf != IntPtr.Zero)
                                {
                                    Marshal.FreeHGlobal(pImageBuf);
                                    pImageBuf = IntPtr.Zero;
                                }

                                pImageBuf = Marshal.AllocHGlobal((int)stFrameOut.stFrameInfo.nWidth * stFrameOut.stFrameInfo.nHeight * 3);
                                if (IntPtr.Zero == pImageBuf)
                                {
                                    break;
                                }
                                nImageBufSize = stFrameOut.stFrameInfo.nWidth * stFrameOut.stFrameInfo.nHeight * 3;
                            }

                            MyCamera.MV_PIXEL_CONVERT_PARAM stPixelConvertParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();

                            stPixelConvertParam.pSrcData = stFrameOut.pBufAddr;//源数据
                            stPixelConvertParam.nWidth = stFrameOut.stFrameInfo.nWidth;//图像宽度
                            stPixelConvertParam.nHeight = stFrameOut.stFrameInfo.nHeight;//图像高度
                            stPixelConvertParam.enSrcPixelType = stFrameOut.stFrameInfo.enPixelType;//源数据的格式
                            stPixelConvertParam.nSrcDataLen = stFrameOut.stFrameInfo.nFrameLen;

                            stPixelConvertParam.nDstBufferSize = (uint)nImageBufSize;
                            stPixelConvertParam.pDstBuffer = pImageBuf;//转换后的数据
                            stPixelConvertParam.enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed;
                            nRet = device.MV_CC_ConvertPixelType_NET(ref stPixelConvertParam);//格式转换
                            if (MyCamera.MV_OK != nRet)
                            {
                                break;
                            }
                            pTemp = pImageBuf;
                        }

                        try
                        {
                            HOperatorSet.GenImageInterleaved(out Hobj, (HTuple)pTemp, (HTuple)"rgb", (HTuple)stFrameOut.stFrameInfo.nWidth, (HTuple)stFrameOut.stFrameInfo.nHeight, -1, "byte", 0, 0, 0, 0, -1, 0);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            break;
                        }
                    }
                    else if (IsMonoPixelFormat(stFrameOut.stFrameInfo.enPixelType))
                    {
                        if (stFrameOut.stFrameInfo.enPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8)
                        {
                            pTemp = stFrameOut.pBufAddr;
                        }
                        else
                        {
                            if (IntPtr.Zero == pImageBuf || nImageBufSize < (stFrameOut.stFrameInfo.nWidth * stFrameOut.stFrameInfo.nHeight))
                            {
                                if (pImageBuf != IntPtr.Zero)
                                {
                                    Marshal.FreeHGlobal(pImageBuf);
                                    pImageBuf = IntPtr.Zero;
                                }

                                pImageBuf = Marshal.AllocHGlobal((int)stFrameOut.stFrameInfo.nWidth * stFrameOut.stFrameInfo.nHeight);
                                if (IntPtr.Zero == pImageBuf)
                                {
                                    break;
                                }
                                nImageBufSize = stFrameOut.stFrameInfo.nWidth * stFrameOut.stFrameInfo.nHeight;
                            }

                            MyCamera.MV_PIXEL_CONVERT_PARAM stPixelConvertParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();

                            stPixelConvertParam.pSrcData = stFrameOut.pBufAddr;//源数据
                            stPixelConvertParam.nWidth = stFrameOut.stFrameInfo.nWidth;//图像宽度
                            stPixelConvertParam.nHeight = stFrameOut.stFrameInfo.nHeight;//图像高度
                            stPixelConvertParam.enSrcPixelType = stFrameOut.stFrameInfo.enPixelType;//源数据的格式
                            stPixelConvertParam.nSrcDataLen = stFrameOut.stFrameInfo.nFrameLen;

                            stPixelConvertParam.nDstBufferSize = (uint)nImageBufSize;
                            stPixelConvertParam.pDstBuffer = pImageBuf;//转换后的数据
                            stPixelConvertParam.enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8;
                            nRet = device.MV_CC_ConvertPixelType_NET(ref stPixelConvertParam);//格式转换
                            if (MyCamera.MV_OK != nRet)
                            {
                                break;
                            }
                            pTemp = pImageBuf;
                        }
                        try
                        {
                            HOperatorSet.GenImage1Extern(out Hobj, "byte", stFrameOut.stFrameInfo.nWidth, stFrameOut.stFrameInfo.nHeight, pTemp, IntPtr.Zero);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            break;
                        }
                    }
                    else
                    {
                        device.MV_CC_FreeImageBuffer_NET(ref stFrameOut);
                        continue;
                    }
                    HalconDisplay(hwindow, Hobj);
                    device.MV_CC_FreeImageBuffer_NET(ref stFrameOut);
                }
                else
                {
                    continue;
                }
            }

            if (pImageBuf != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(pImageBuf);
                pImageBuf = IntPtr.Zero;
            }
        }
        private void bnTriggerExec_Click(object sender, EventArgs e)
        {
           
        }

        private void btnTrigger_Click(object sender, EventArgs e)
        {
            // ch: 触发命令 || en: Trigger command
            int nRet = m_pMyCamera.MV_CC_SetCommandValue_NET("TriggerSoftware");
            if (MyCamera.MV_OK != nRet)
            {
                MessageBox.Show("Trigger Fail");
            }
        }

        private void btnCtinu_Click(object sender, EventArgs e)
        {
            


            int nRet = m_pMyCamera.MV_CC_SetEnumValue_NET("TriggerMode", 0);
            if (nRet != MyCamera.MV_OK)
            {
                MessageBox.Show("Set TriggerMode Fail");
                return;
            }
            // ch:开启抓图 | en:start grab
             nRet = m_pMyCamera.MV_CC_StartGrabbing_NET();
            if (MyCamera.MV_OK != nRet)
            {
                MessageBox.Show("Start Grabbing Fail");
                return;
            }
            m_bGrabbing = true;

            Thread hReceiveImageThreadHandle = new Thread(ReceiveImageWorkThread);
            hReceiveImageThreadHandle.Start(m_pMyCamera);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            int nRet = m_pMyCamera.MV_CC_StopGrabbing_NET();
            if (nRet != MyCamera.MV_OK)
            {
                MessageBox.Show("Stop Grabbing Fail");
            }
            m_bGrabbing = false;
        }

        

        private void btnRoi_Click(object sender, EventArgs e)
        {
            if (doRoi == null)
            {
                //创建一个矩形的显示实例
                //doRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, 100, 100, 210, 210);
                doRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE1, 100, 100, 210, 210);
                doRoi.SetDrawingObjectParams("color", "green");
                //挂靠实例到HSmartWindowControl控件
                hSmartWindowControl1.HalconWindow.AttachDrawingObjectToWindow(doRoi);
            }
            else
            {
                hSmartWindowControl1.HalconWindow.DetachDrawingObjectFromWindow(doRoi);//这里这句可以不要
                doRoi = null;
            }

        }
        private bool actionK(HWindow ho_WHD, HObject i_mage,string template)
        {


            HObject ho_Image, ho_Edges, ho_Circle = null, cross = null;

            HObject ho_ModelTrans1 = null;
            HObject ho_ModelContours, ho_ModelTrans = null;
           
            HTuple hv_Angle = null, hv_Scale = null, hv_Score = null, hv_Column = null, Phv_Row = null, Phv_Column = null;
            HTuple hv_Row = null;
          


            HTuple hv_I = null, hv_HomMat2DRotate = new HTuple(), hv_HomMat2DScale = new HTuple();
            HTuple hv_HomMat2DRotate1 = new HTuple(), hv_HomMat2DScale1 = new HTuple();
            HTuple hv_ModelID = null;
          
           
            string strMsg = string.Empty;
            string fn;
            fn = Application.StartupPath;
         
            
            HOperatorSet.GenEmptyObj(out ho_Image);
            HOperatorSet.Rgb1ToGray(i_mage, out ho_Image);
            
            try
            {

                 HOperatorSet.DispObj(ho_Image, ho_WHD);// ch 显示 || en: display
                // ho_WHD.DispObj(ho_Image);
                i_mage.Dispose();
                fn = fn + "/" + template + ".shm";
                fn = fn.Replace("\\", "/");//water gauge position
              

                HOperatorSet.ReadShapeModel(fn, out hv_ModelID);
                HOperatorSet.FindScaledShapeModel(ho_Image, hv_ModelID, 0, 6.29, 0.8, 1.0,
                      0.5, 1, 0.5, "least_squares", 5, 0.8, out hv_Row, out hv_Column, out hv_Angle,
                      out hv_Scale, out hv_Score);


                HOperatorSet.GetShapeModelContours(out ho_ModelContours, hv_ModelID, 1);
                HOperatorSet.ClearShapeModel(hv_ModelID);

                for (hv_I = 0; (int)hv_I <= (int)((new HTuple(hv_Score.TupleLength())) - 1); hv_I = (int)hv_I + 1)
                {
                    //HOperatorSet.SetColor(WindowHandle, "red");

                    HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_Row.TupleSelect(hv_I), hv_Column.TupleSelect(
                        hv_I), hv_Angle.TupleSelect(hv_I), out hv_HomMat2DRotate);

                    HOperatorSet.HomMat2dScale(hv_HomMat2DRotate, hv_Scale.TupleSelect(hv_I),
                        hv_Scale.TupleSelect(hv_I), hv_Row.TupleSelect(hv_I), hv_Column.TupleSelect(
                        hv_I), out hv_HomMat2DScale);
                   
                    HOperatorSet.AffineTransContourXld(ho_ModelContours, out ho_ModelTrans, hv_HomMat2DScale);


                    //HOperatorSet.DispObj(ho_ModelTrans, WindowHandle);
                    // ho_WHD.DispObj(ho_ModelTrans, "blue");
                    HOperatorSet.SetColor(ho_WHD, "red");
                    HOperatorSet.DispObj(ho_ModelTrans, ho_WHD);
                    // HOperatorSet.DispObj(ho_Image, ho_WHD);// ch 显示 || en: display



                    x = hv_Row;
                    y= hv_Column;
                    angle = hv_Angle.TupleSelect(hv_I).TupleDeg();

                    //if (CAutoGL.VisionR > 180)
                    //{
                    //    CAutoGL.VisionR = CAutoGL.VisionR - 360;
                    //}

                    //HOperatorSet.GenCircle(out ho_Circle, hv_Row.TupleSelect(hv_I), hv_Column.TupleSelect(hv_I), 100);

                    //HOperatorSet.DispObj(ho_Circle1, WindowHandle);
                    // ho_WHD.DispObj(ho_Circle, "blue");
                    // HOperatorSet.DispObj(ho_Circle, ho_WHD);
                    //ho_Circle.Dispose();


                    // Phv_Row = hv_Row.TupleSelect(hv_I) + CAutoGL.radius * Math.Sin((CAutoGL.angle - CAutoGL.VisionR) * 3.141 / 180);
                    // Phv_Column = hv_Column.TupleSelect(hv_I) + CAutoGL.radius * Math.Cos((CAutoGL.angle - CAutoGL.VisionR) * 3.141 / 180);
                    /// CAutoGL.VisionX = Phv_Row;
                    //CAutoGL.VisionY = Phv_Column;


                    HOperatorSet.SetColor(ho_WHD, "green");
                    HOperatorSet.GenCrossContourXld(out cross, hv_Row, hv_Column, 100, 0);
                    //HOperatorSet.GenCircleContourXld(out cross, hv_Row, hv_Column, 100, 0);
                    HOperatorSet.DispObj(cross, ho_WHD);
                   // ho_WHD.DispObj(cross, "blue");

                    //HOperatorSet.GenCrossContourXld(out cross, Phv_Row, Phv_Column, 40, 0);
                    //HOperatorSet.DispObj(cross, WindowHandle);
                    //ho_WHD.DispObj(cross, "red");

                    cross.Dispose();



                   // HOperatorSet.SetColor(ho_WHD.HWindowHalconID, "red");
                   // HOperatorSet.SetTposition(ho_WHD.HWindowHalconID, hv_Row.TupleSelect(hv_I) - 50, hv_Column.TupleSelect(hv_I) - 600);
                   // HOperatorSet.WriteString(ho_WHD.HWindowHalconID, "Pos1:" + CAutoGL.VisionX.ToString("0.00") + ";" + CAutoGL.VisionY.ToString("0.00") + ";" + CAutoGL.VisionR.ToString("0.00"));
                    //HOperatorSet.SetColor(WindowHandle, "blue");



                }

                ho_Image.Dispose();

              
               // ho_ModelTrans.Dispose();
               // ho_ModelTrans1.Dispose();
                return true;
               
            }
            catch (Exception ex)
            {
                ho_Image.Dispose();
               
                return false;
            }
        }
    }
       
    }

